package org.fhawk.tinyspring.orm;

import org.apache.commons.dbutils.BeanProcessor;
import org.apache.commons.dbutils.ColumnHandler;
import org.fhawk.tinyspring.core.ClassHelper;
import org.fhawk.tinyspring.util.ObjectUtil;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class CustomBeanProcessor extends BeanProcessor {
    private static final List<ColumnHandler> columnHandlers;

    static {
        List<Class<?>> classes = ClassHelper.getBasePackageClassListBySuperClass(ColumnHandler.class);
        columnHandlers = new ArrayList<>(classes.size());
        for (Class<?> clazz : classes) {
            Object o = ObjectUtil.newInstance(clazz.getName());
            if (o instanceof ColumnHandler) {
                columnHandlers.add((ColumnHandler) o);
            }
        }
    }

    @Override
    protected Object processColumn(ResultSet rs, int index, Class<?> propType) throws SQLException {
        Object retval = super.processColumn(rs, index, propType);
        if (!propType.isPrimitive() && retval == null) {
            return null;
        }
        for (ColumnHandler handler : columnHandlers) {
            if (handler.match(propType)) {
                retval = handler.apply(rs, index);
                break;
            }
        }
        return retval;
    }
}
